// pages/category/category.js
import {request} from "../../request/index.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //左侧菜单数据
    leftList: [],
    rightList: [],
    currentIndex: 0,
    scrollTop: 0
    //右侧菜单数据
  },
  //接口返回数据
  Cates: [],
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    /*
    1. 先判断一下本地储存是否有旧数据
    */
   const Cates = wx.getStorageSync('cates');
   if (Cates && Date.now() - Cates.time < 100000) {
     //如果有缓存则直接使用缓存
      let leftList = this.Cates.map(v=>v.cat_name);
      //右侧数据
      let rightList = this.Cates[0].children;
      this.setData({
        leftList,
        rightList
      });
      return;
   }
   //否则重新加载
    this.getCates();
  },
//获取分类数据
  async getCates() {
    // request({
    //   "url": "/categories",
    // }).then(res => {
    //   this.Cates = res.data.message;
    //   //把接口的数据存入本地
    //   wx.setStorageSync('cates', {
    //     time: Date.now(),
    //     data: this.Cates
    //   });
    //   //左侧数据
    //   let leftList = this.Cates.map(v=>v.cat_name);
    //   //右侧数据
    //   let rightList = this.Cates[0].children;
    //   this.setData({
    //     leftList,
    //     rightList
    //   });
    // });
    /*es7 async方法代码同步，方法外异步 */
    const res = await request({"url": "/categories"});
    this.Cates = res.data.message;
      //把接口的数据存入本地
      wx.setStorageSync('cates', {
        time: Date.now(),
        data: this.Cates
      });
      //左侧数据
      let leftList = this.Cates.map(v=>v.cat_name);
      //右侧数据
      let rightList = this.Cates[0].children;
      this.setData({
        leftList,
        rightList
      });
  },
  //左侧菜单的点击事件
  itemTap(e) {
    const currentIndex = e.target.dataset.index;
    let rightList = this.Cates[currentIndex].children;
    this.setData({
      currentIndex,
      rightList,
       //重新设置距离顶部的距离
      scrollTop: 0
    });
  }
})